//#include "stdafx.h"
#include "FileStorage.h"

FileStorage :: FileStorage()
{}

void FileStorage :: readFromFile(vector<Date>& currentList, vector<Date>& historyList)
{
	ProcessList readObjects;
	ProcessHistory readHistory;
	struct Task currentTask;
	Date currentDate=currentList[0];
	int index;
	stringstream str;
	vector<string> storedDetails;
	ifstream textFile("Tempus.txt");
	string temp = "";

	textFile.seekg(0, ios::end);  
	 int length = textFile.tellg();
 
	if(length!=0)
    {
		textFile.seekg(0, ios::beg);  
		while(!textFile.eof())
		{					
			for (int i=0; i<7; i++)
			{
				getline(textFile,temp);
				storedDetails.push_back(temp);
			}
			currentTask.id = storedDetails.at(0);
			currentTask.name = storedDetails.at(1);
			currentTask.time = storedDetails.at(2);
			currentTask.location = storedDetails.at(3);
			currentTask.deadline = storedDetails.at(4);
			currentTask.status= storedDetails.at(5);
			storedDetails.clear();

			if (currentTask.location=="undefined")
				currentTask.location="";
			currentTask.date=currentTask.id.substr(0,8);
			Date newDate=currentDate.dateStringToObject(currentTask.date);
			if(currentDate.compareDates(newDate)>=0)
				readObjects.addEvent(currentList, currentTask);
			else
				readHistory.addEvent(historyList, currentTask);
		}
	}
	textFile.close();
    // else cout << "Error in opening file!" << endl;
}

void FileStorage :: writeToFile(vector<Date>& currentList, vector<Date>& historyList)
{
	ofstream textFile("Tempus.txt");
	string textToWrite;
	textToWrite = transferText(historyList, "history");
	textFile << textToWrite;

	textToWrite = transferText(currentList, "current");
	textToWrite = trim(textToWrite);
	textFile << textToWrite;
	textFile.close();
}

string FileStorage::transferText(vector<Date>list, string type)
{
	stringstream allInfo;
	Event currentEvent;
	int index=0;

	for (int i=0; i <list.size(); i++)
	{
		if (type=="history")
		{
			index = list.size()-1-i;
		}
		else
			index = i;

		for (int j=0; j < list[index].getEventListLength(); j++)
		{
			currentEvent = list[index].getEvent(j);

			allInfo << currentEvent.getId() << endl;
			allInfo << currentEvent.getName() << endl;
			allInfo << currentEvent.getTime() << endl;
		
			if (currentEvent.getLocation()=="")
					allInfo << "undefined\n";
			else
				allInfo << currentEvent.getLocation() << endl;
			allInfo << currentEvent.getEventType() << endl;
			allInfo << currentEvent.getEventStatus() << endl;
			allInfo << endl;
		}
    }

	return allInfo.str();
}


string FileStorage::trim(string text){
	
	string trimmedText;
	int startPos=text.find_first_not_of('\n');
	int endPos=text.find_last_not_of('\n');
	if(startPos==-1)
		trimmedText="";
	else
		trimmedText=text.substr(startPos,endPos-startPos+1);

	return trimmedText;
}
